package com.whmskj.xjlhbc.mobile.controller;

import com.whmskj.xjlhbc.core.AjaxResult;
import com.whmskj.xjlhbc.domain.MesDbDayDetail;
import com.whmskj.xjlhbc.mobile.mapper.WorkshopEnergyConsumptionMapper;
import com.whmskj.xjlhbc.mobile.vo.MeterReadingVerificationVO;
import com.whmskj.xjlhbc.service.IPersonnelManagementDataSheetsService;
import com.whmskj.xjlhbc.domain.PersonnelManagementDataSheets;
import com.whmskj.xjlhbc.domain.CorpMember;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 车间能耗Controller
 * 抄表核查和抄表数据修改接口
 */
@RestController
@Tag(name = "车间能耗", description = "车间能耗管理接口")
@RequestMapping("/mobile/workshop-energy")
public class WorkshopEnergyConsumptionController {

    @Autowired
    private WorkshopEnergyConsumptionMapper workshopEnergyConsumptionMapper;
    
    @Autowired
    private IPersonnelManagementDataSheetsService personnelManagementDataSheetsService;

    /**
     * 抄表核查接口
     * @param date 核查日期
     * @return 核查结果
     */
    @GetMapping("/meter-reading-verification")
    @Operation(summary = "抄表核查", description = "获取指定日期的抄表核查数据，按配电室分组")
    public AjaxResult meterReadingVerification(
            @Parameter(description = "核查日期", example = "2025-09-30") 
            @RequestParam @DateTimeFormat(pattern = "yyyy-MM-dd") Date date) {
        
        try {
            // 查询指定日期的抄表数据
            List<MesDbDayDetail> meterData = workshopEnergyConsumptionMapper.selectByDate(date);
            
            // 按配电室分组
            Map<String, List<MesDbDayDetail>> groupedByRoom = meterData.stream()
                    .collect(Collectors.groupingBy(MesDbDayDetail::getPdsname));

            List<MeterReadingVerificationVO> result = new ArrayList<>();
            SimpleDateFormat timeFormat = new SimpleDateFormat("HH:mm");
            
            for (Map.Entry<String, List<MesDbDayDetail>> entry : groupedByRoom.entrySet()) {
                MeterReadingVerificationVO roomVO = new MeterReadingVerificationVO();
                roomVO.setDistributionRoomName(entry.getKey());
                roomVO.setDistributionRoomCode(entry.getValue().get(0).getMacname());
                
                List<MeterReadingVerificationVO.MeterData> meterList = entry.getValue().stream()
                        .map(data -> {
                            MeterReadingVerificationVO.MeterData meterDataVO = new MeterReadingVerificationVO.MeterData();
                            meterDataVO.setId(data.getId());
                            meterDataVO.setMeterName(data.getDbname());
                            meterDataVO.setMeterReading(data.getA720());
                            meterDataVO.setMeterId(data.getMacid());
                            meterDataVO.setStatus(data.getStatus());
                            
                            // 格式化抄表时间
                            if (data.getTs() != null) {
                                meterDataVO.setReadingTime(timeFormat.format(data.getTs()));
                            }
                            
                            return meterDataVO;
                        })
                        .collect(Collectors.toList());
                
                roomVO.setMeterDataList(meterList);
                result.add(roomVO);
            }
            
            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("查询抄表核查数据失败: " + e.getMessage());
        }
    }

    /**
     * 抄表数据修改接口
     * @param id 记录ID
     * @param a720 新的表数
     * @param remarks 备注
     * @return 修改结果
     */
    @PostMapping("/modify-meter-reading")
    @Operation(summary = "抄表数据修改", description = "修改指定记录的抄表数据")
    public AjaxResult modifyMeterReading(
            @Parameter(description = "记录ID", example = "1") 
            @RequestParam(required = false) Long id,
            @Parameter(description = "新的表数")
            @RequestParam(required = false) Double a720,
            @Parameter(description = "备注", example = "手动修正") 
            @RequestParam(required = false) String remarks,
            @RequestBody(required = false) Map<String, Object> requestBody) {

        if (requestBody != null) {
            if (id == null && requestBody.containsKey("id")) {
                id = Long.valueOf(requestBody.get("id").toString());
            }
            if (a720 == null && requestBody.containsKey("a720")) {
                a720 = Double.valueOf(requestBody.get("a720").toString());
            }
            if (remarks == null && requestBody.containsKey("remarks")) {
                remarks = requestBody.get("remarks").toString();
            }
        }
        
        try {
            // 参数验证
            if (id == null) {
                return AjaxResult.error("记录ID不能为空");
            }
            if (a720 == null) {
                return AjaxResult.error("表数不能为空");
            }
            
            // 查询原记录
            MesDbDayDetail record = workshopEnergyConsumptionMapper.selectById(id);
            if (record == null) {
                return AjaxResult.error("记录不存在");
            }
            
            // 更新表数和备注
            record.setA720(a720);
            if (remarks != null && !remarks.isEmpty()) {
                record.setReplacingRemarks(remarks);
            }
            
            // 获取当前登录用户信息
            CorpMember currentUser = personnelManagementDataSheetsService.getCorpMemberByLogin();
            String userName = currentUser.getNick();
            String memberId =  currentUser.getMemberId();
            
            // 设置抄表核查人为当前登录用户的姓名
            record.setCopyCheck(userName);
            // 设置维护人为当前登录用户的memberId
            record.setOtherOrganiser(memberId);
            
            // 设置维护时间为当前提交时间
            Date currentTime = new Date();
            record.setMaintenanceTime(currentTime);
            
            // 保存更新
            int result = workshopEnergyConsumptionMapper.updateById(record);
            if (result > 0) {
                return AjaxResult.success("抄表数据修改成功");
            } else {
                return AjaxResult.error("抄表数据修改失败");
            }
        } catch (Exception e) {
            return AjaxResult.error("抄表数据修改失败: " + e.getMessage());
        }
    }
}
